import { Component, OnInit, Injector, ViewChild } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { Table } from 'primeng/table';
import { Paginator, LazyLoadEvent } from 'primeng/primeng';
import { PrimengTableHelper } from '@shared/helpers/PrimengTableHelper';
import {
    ListDtoExtensionsItem,
    Stock_BillListDto,
    StockZT_IntoBillItemServiceProxy,
    Stock_IntoMarketBaseListDto,
    UserDataPermissionServiceProxy,
    StockZT_RoomServiceProxy,
    Stock_IntoMarketBaseExcelImportDto,
    Stock_IntoMarketBaseExcelImportOutput
} from '@shared/service-proxies/stock-service-proxies';

import { finalize } from 'rxjs/operators';
import { AppConsts } from '@shared/AppConsts';
import { CreateOrEditMarketIntoBillItemModalComponent } from './create-or-edit-market-into-bill-item-modal.component';

@Component({
    templateUrl: './market-into.component.html',
    animations: [appModuleAnimation()],
    styles: ['.nowrap {overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}']
})
export class MarketIntoComponent extends AppComponentBase implements OnInit {
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;

    @ViewChild('detailDataTable') detailDataTable: Table;
    @ViewChild('detailPaginator') detailPaginator: Paginator;
    @ViewChild('createOrEditMarketIntoBillItemModal')
    createOrEditMarketIntoBillItemModal: CreateOrEditMarketIntoBillItemModalComponent;

    // filters
    materialNameFilter = '';
    materialCodeFilter = '';
    certificationNumFilter = '';
    reCheckFilter = '';
    supplierFilter = '';
    warehouseNameFilter = '';
    userDataPermissions;
    inventBatchIDFilter = '';
    extensions: Array<ListDtoExtensionsItem>;
    detialExtensions: Array<ListDtoExtensionsItem>;
    detailPrimengTableHelper: PrimengTableHelper;
    totalprice = 0;
    selectedBill: Stock_BillListDto;
    selectedBillItem = new Stock_IntoMarketBaseListDto();
    billStatusOptions = [
        { label: '全部', value: undefined },
        { label: '新建', value: '新建' },
        { label: '已提交', value: '已提交' },
        { label: '已入库', value: '已入库' }
    ];
    purchaseOption;
    billstatus = '';
    billcode = '';
    roomOption;
    selectedPurchaseType;
    operatorOptions = [{ label: '当前登录人', value: '当前登录人' }, { label: '全部', value: undefined }];
    operator = '';
    selectedWareHouse;
    PRDeptOption;
    selectedPRDept;
    constructor(
        injector: Injector,
        private _billService: StockZT_IntoBillItemServiceProxy,
        private _userDataPermissionServiceProxy: UserDataPermissionServiceProxy,
        private _stockZT_RoomServiceProxy: StockZT_RoomServiceProxy
    ) {
        super(injector);
        this.detailPrimengTableHelper = new PrimengTableHelper();
    }

    ngOnInit(): void {
        this._userDataPermissionServiceProxy.getUserDataPermissions('Warehouses').subscribe(result => {
            this._stockZT_RoomServiceProxy.getRoomListByDepts(result.items, '市采物资库', '').subscribe(result2 => {
                this.roomOption = result2.items.map(e => {
                    return {
                        label: e.displayText,
                        value: e
                    };
                });
                this._stockZT_RoomServiceProxy.getRoomListByUserRole('市采物资库').subscribe(result2 => {
                    this.selectedWareHouse = result2.items;
                    // this.getBills();
                });

                // this.selectedWareHouse = result2.items;

                // this._billService.getPurchaseTypeByDataItem().subscribe(result1 => {
                //     this.purchaseOption = result1.map(e => {
                //         return {
                //             label: e.displayText,
                //             value: e
                //         };
                //     });
                //     this.selectedPurchaseType = result1;
                //     this.getBills();
                // });
            });
        });
        this._billService.loadMarketIntoBaseData().subscribe(result => {
            // this.roomOption = result[2].map(e => {
            //     return {
            //         label: e.displayText,
            //         value: e
            //     };
            // });
            // this.selectedWareHouse = result[2];

            this.purchaseOption = result[1].map(e => {
                return {
                    label: e.displayText,
                    value: e
                };
            });
            this.selectedPurchaseType = result[1];

            this.PRDeptOption = result[0].map(e => {
                return {
                    label: e.displayText,
                    value: e
                };
            });
            /* this.selectedPRDept = result[0]; */

            this.getBills();
        });
    }
    onUpload(event) {
        // let list = event as Array<any>;
        let list = event.fileData[0].sheetJson;
        console.log(list)
        let customerImportIntoList = list.map(el => {
            return {
                serialNumber: el.序号,
                deliveryDate: el.出库日期,
                materialCode: el.物料编码,
                name: el.名称,
                materialInformation: el.物资信息,
                model: el.型号,
                specifications: el.规格,
                accuracy: el.精度,
                brand: el.品牌,
                articleNumber: el.货号,
                unit: el.单位,
                firmOfferInventory: el.实盘库存数,
                unitPrice: el.单价,
                amountOfMoney: el.金额,
                supplier: el.供货单位,
                userDept: el.使用单位,
                remark: el.备注
            };
        }) as Array<Stock_IntoMarketBaseExcelImportDto>;
        this.message.confirm(
            '确认导入这' + customerImportIntoList.length + '条数据吗？',
            this.l('AreYouSure'),
            async (isConfirmed) => {
                if (isConfirmed) {
                    // this.primengTableHelper.showLoadingIndicator();
                    abp.ui.setBusy(undefined, `0 / ${customerImportIntoList.length}`);
                    let errorList = new Array<Stock_IntoMarketBaseExcelImportOutput>()
                    let currentIndex = 0
                    const IMPORT_STEP_LENGTH = 10
                    while (currentIndex < customerImportIntoList.length) {
                        let currentStepLength = IMPORT_STEP_LENGTH
                        if (customerImportIntoList.length - currentIndex < IMPORT_STEP_LENGTH) {
                            currentStepLength = customerImportIntoList.length - currentIndex
                        }
                        let result = await this.uploadStep(customerImportIntoList.slice(currentIndex, currentIndex + currentStepLength))
                        if (result && result.length > 0) {
                            errorList = errorList.concat(result)
                            console.log(result)
                        }
                        currentIndex += currentStepLength
                        abp.ui.setBusy(undefined, `${currentIndex} / ${customerImportIntoList.length}`);
                        console.log(`导入进度：${currentIndex} / ${customerImportIntoList.length}`)
                    }
                    abp.ui.clearBusy();
                    if (errorList.length > 0) {
                        //导出数据
                        console.log(errorList)
                        this.notify.error('部分导入成功');
                    } else {
                        this.notify.success('导入数据成功');
                    }
                    this.getBills()
                    // this.notify.success('导入数据成功');
                    // this.primengTableHelper.hideLoadingIndicator();
                }
            }
        );
    }
    uploadStep(list: Array<Stock_IntoMarketBaseExcelImportDto>) {
        return new Promise<Stock_IntoMarketBaseExcelImportOutput[]>((resolve, reject) => {
            this._billService
                .stock_IntoMarketBaseImportExcel(list)
                .subscribe(result => {
                    //this.getModels();
                    //this.notify.success('导入数据成功');
                    //this.primengTableHelper.hideLoadingIndicator();
                    resolve(result)
                });
        })
    }
    getBills(event?: LazyLoadEvent, resetpage?: boolean) {
        if (!this.selectedWareHouse || !this.selectedPurchaseType) {
            return;
        }
        if (this.primengTableHelper.shouldResetPaging(event) || event.first == undefined) {
            if (resetpage == undefined) {
                this.paginator.changePage(0);
                return;
            }
        }

        this.primengTableHelper.showLoadingIndicator();

        this._billService
            .getIntoMarketBaseListExtension(
                this.supplierFilter,
                this.materialCodeFilter,
                this.materialNameFilter,
                this.certificationNumFilter,
                this.reCheckFilter,
                this.inventBatchIDFilter,
                this.selectedWareHouse,
                this.selectedPurchaseType,
                this.billcode,
                this.billstatus,
                this.operator,
                this.selectedPRDept,
                this.primengTableHelper.getSorting(this.dataTable),
                this.primengTableHelper.getMaxResultCount(this.paginator, event),
                this.primengTableHelper.getSkipCount(this.paginator, event)
            )
            .subscribe(result => {
                this.extensions = result.items;
                this.primengTableHelper.totalRecordsCount = result.stock_IntoMarketBaseList.totalCount;
                this.primengTableHelper.records = result.stock_IntoMarketBaseList.items;
                this.primengTableHelper.hideLoadingIndicator();

                // this.detailPrimengTableHelper.totalRecordsCount = 0;
                // this.detailPrimengTableHelper.records = null;
                this.detailPrimengTableHelper = new PrimengTableHelper();
                this.selectedBill = null;
                this.selectedBillItem = null;
            });
    }
    insertmarket(billid, event) {
        this.createOrEditMarketIntoBillItemModal.show(billid, undefined, event, this.selectedBillItem.id);
    }
    submitBill() {
        if (!this.selectedBill) {
            return;
        }

        this.message.confirm('确认提交该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .submitMarketIntoBillBase(this.selectedBill.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success('提交成功');
                        /* this.getBills(undefined, true); */
                        this.selectedBill.f_BillStatus = '已提交';
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }

    postBill() {
        if (!this.selectedBill) {
            return;
        }

        this.message.confirm('确认过账该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .postIntoBillBase(this.selectedBill.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success('过账成功');
                        /* this.getBills(undefined, true); */
                        this.selectedBill.f_BillStatus = '已入库';
                        this.selectedBill.f_Posted = '已过账';
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }

    sendBackBill() {
        if (!this.selectedBill) {
            return;
        }

        this.message.confirm('确认退回该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .sendBackIntoBillBase(this.selectedBill.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success(this.l('更新成功'));
                        /* this.getBills(undefined, true); */
                        this.selectedBill.f_BillStatus = '新建';
                        this.getBillItems();
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }
    clearQuery() {
        this.materialNameFilter = '';
        this.materialCodeFilter = '';
        this.certificationNumFilter = '';
        this.reCheckFilter = '';
        this.supplierFilter = '';
        this.warehouseNameFilter = '';
        this.userDataPermissions;
        this.inventBatchIDFilter = '';
        this.billstatus = '';
        this.billcode = '';
    }
    printBillList() {
        if (this.selectedBill === null || this.selectedBill.id === undefined) {
            this.notify.error('请选择需要打印的单据！');
        } else {
            //装配类派工单
            window.open(
                AppConsts.printAddr +
                '/webroot/decision/view/report?viewlet=erp/SCWZRKDHZ.cpt&BillId=' +
                this.selectedBill.id
            );
        }
    }

    printAll() {
        window.open(AppConsts.printAddr + '/webroot/decision/view/report?viewlet=erp/市采物资入库单-汇总.cpt');
    }

    getBillItems(event?: LazyLoadEvent, clear?: boolean) {
        if (!this.selectedBill) {
            return;
        }
        if (this.detailPrimengTableHelper.shouldResetPaging(event)) {
            if (clear == undefined) {
                this.detailPaginator.changePage(0);
                return;
            }
        }

        this.primengTableHelper.showLoadingIndicator();

        this._billService
            .getIntoMarketItemListExtension(
                this.selectedBill.id,
                this.detailPrimengTableHelper.getSorting(this.detailDataTable),
                this.detailPrimengTableHelper.getMaxResultCount(this.detailPaginator, event),
                this.detailPrimengTableHelper.getSkipCount(this.detailPaginator, event)
            )
            .subscribe(result => {
                this.detialExtensions = result.items;
                this.detailPrimengTableHelper.totalRecordsCount = result.stock_IntoMarketItemList.totalCount;
                this.detailPrimengTableHelper.records = result.stock_IntoMarketItemList.items;
                this._billService.getIntoMarketItemsTotalPrice(this.selectedBill.id).subscribe(totalprice => {
                    this.totalprice = totalprice;
                });
                this.primengTableHelper.hideLoadingIndicator();
                if (!clear) {
                    this.selectedBillItem = null;
                }
            });
    }

    deleteBill() {
        if (!this.selectedBill) {
            return;
        }

        this.message.confirm('确认删除该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .deleteIntoBillBase(this.selectedBill.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success(this.l('SuccessfullyDeleted'));
                        this.getBills();
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }

    deleteBillItem() {
        if (!this.selectedBillItem) {
            return;
        }

        this.message.confirm('确认删除该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .deleteIntoBillItem(this.selectedBillItem.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this._billService.updateBillItemSort(this.selectedBill.id).subscribe(() => {
                            this.notify.success(this.l('SuccessfullyDeleted'));
                            this.getBillItems();
                            this.primengTableHelper.hideLoadingIndicator();
                        });
                    });
            }
        });
    }

    // 上移
    moveUp() {
        if (!this.selectedBillItem) {
            return;
        }
        this.primengTableHelper.showLoadingIndicator();
        this._billService
            .moveUpIntoItem(this.selectedBillItem.id)
            .pipe(
                finalize(() => {
                    this.primengTableHelper.hideLoadingIndicator();
                })
            )
            .subscribe(() => {
                this.getBillItems(undefined, true);
                this.primengTableHelper.hideLoadingIndicator();
            });
    }

    // 下移
    moveDown() {
        if (!this.selectedBillItem) {
            return;
        }
        this.primengTableHelper.showLoadingIndicator();
        this._billService
            .moveDownIntoItem(this.selectedBillItem.id)
            .pipe(
                finalize(() => {
                    this.primengTableHelper.hideLoadingIndicator();
                })
            )
            .subscribe(() => {
                this.getBillItems(undefined, true);
                this.primengTableHelper.hideLoadingIndicator();
            });
    }
}
